package com.gtc.zsk.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gtc.zsk.annotation.AuthCheck;
import com.gtc.zsk.common.*;
import com.gtc.zsk.config.WxOpenConfig;
import com.gtc.zsk.constant.UserConstant;
import com.gtc.zsk.exception.BusinessException;
import com.gtc.zsk.exception.ThrowUtils;
import com.gtc.zsk.model.dto.managepwd.UpdateManagePwdRequest;
import com.gtc.zsk.model.dto.user.*;
import com.gtc.zsk.model.entity.User;
import com.gtc.zsk.model.entity.VipBankUser;
import com.gtc.zsk.model.vo.LoginUserVO;
import com.gtc.zsk.model.vo.UserVO;
import com.gtc.zsk.service.UserService;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gtc.zsk.service.VipBankUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static com.gtc.zsk.constant.UserConstant.*;
import static com.gtc.zsk.service.impl.UserServiceImpl.SALT;

/**
 * 用户接口
 *
 * @author <a href="https://github.com/ligtc">程序员鱼皮</a>
 * @from <a href="https://gtc.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private VipBankUserService vipBankUserService;

    @Resource
    private WxOpenConfig wxOpenConfig;

    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String userName = userRegisterRequest.getUserName();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, userName);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户登录（微信开放平台）
     */
    @GetMapping("/login/wx_open")
    public BaseResponse<LoginUserVO> userLoginByWxOpen(HttpServletRequest request, HttpServletResponse response,
            @RequestParam("code") String code) {
        WxOAuth2AccessToken accessToken;
        try {
            WxMpService wxService = wxOpenConfig.getWxMpService();
            accessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(accessToken, code);
            String unionId = userInfo.getUnionId();
            String mpOpenId = userInfo.getOpenid();
            if (StringUtils.isAnyBlank(unionId, mpOpenId)) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
            }
            return ResultUtils.success(userService.userLoginByMpOpen(userInfo, request));
        } catch (Exception e) {
            log.error("userLoginByWxOpen error", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
        }
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        userService.validUser(user, true);
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        user.setUserAvatar(defaultAvatar[(int)Math.round(Math.random())]);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Object userObj = StpUtil.getSession().get(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (deleteRequest.getId().equals(currentUser.getId()))
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "您差点就删掉自己了~");
        if (deleteRequest.getId().longValue() == 1871810916349243394L)
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "您不能删除该尊贵的用户！！！");
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (userUpdateRequest.getId().longValue() == 1871810916349243394L && loginUser.getId().longValue() != 1871810916349243394L)
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "您没有权限修改最高管理员！");
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        userService.validUser(user, false);
        String userRole = user.getUserRole();
        if (StringUtils.isNotBlank(userRole) && DEFAULT_ROLE.equals(userRole)){
            LambdaQueryWrapper<VipBankUser> lambdaQueryWrapper = Wrappers.lambdaQuery(VipBankUser.class)
                    .select(VipBankUser::getId)
                    .eq(VipBankUser::getUserId, user.getId());
            List<VipBankUser> vipBankUserList = vipBankUserService.list(lambdaQueryWrapper);
            if (CollUtil.isNotEmpty(vipBankUserList))
                user.setVipLevel(Integer.min(vipBankUserList.size(), 6));
            else
                user.setVipLevel(0);
        }
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("/edit")
    public BaseResponse<UserVO> editUser(@RequestBody UserEditRequest userEditRequest, HttpServletRequest request) {
        if (userEditRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 列举管理员的操作
//        boolean adminOperation = ObjectUtils.isNotEmpty(userUpdateRequest.getBalance())
//                || StringUtils.isNotBlank(userUpdateRequest.getUserRole())
//                || StringUtils.isNotBlank(userUpdateRequest.getUserPassword());
//        boolean adminOperation = StringUtils.isNotBlank(userUpdateRequest.getUserRole())
//                || StringUtils.isNotBlank(userUpdateRequest.getUserPassword());
        // 校验是否登录
        User loginUser = userService.getLoginUser(request);
        // 处理管理员业务,不是管理员抛异常
//        if (adminOperation && !loginUser.getUserRole().equals("admin")) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//        }
//        if (!loginUser.getUserRole().equals("admin") && !userUpdateRequest.getId().equals(loginUser.getId())) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "只有本人或管理员可以修改");
//        }
//        if (userUpdateRequest.getId().longValue() == 1871810916349243394L && loginUser.getId().longValue() != 1871810916349243394L)
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "您没有权限修改最高管理员！");
        User user = new User();
        BeanUtils.copyProperties(userEditRequest, user);
        // 参数校验
        userService.validUser(user, false);
        // 强制设置id为当前用户id（防止越权修改）
        user.setId(loginUser.getId());
        boolean result =userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userService.getById(user.getId()), userVO);
        return ResultUtils.success(userVO);
    }

    @PostMapping("/update/pwd")
    public BaseResponse<Long> updateUserPwd(@RequestBody UpdateManagePwdRequest updateManagePwdRequest) {
        long id = updateManagePwdRequest.getId().longValue();
        if (ObjectUtils.anyNull(updateManagePwdRequest, id) || id <= 0)
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        String oldPwd = updateManagePwdRequest.getOldPwd();
        String newPwd = updateManagePwdRequest.getNewPwd();
        String checkNewPwd = updateManagePwdRequest.getCheckNewPwd();
        if (StringUtils.isAnyBlank(oldPwd, newPwd, checkNewPwd))
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "原密码、新密码、确认密码都不能为空!");
        if (!newPwd.equals(checkNewPwd))
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次新密码输入不一致!");
        if (newPwd.length() < 8 || newPwd.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "设置密码过短");
        }
        String encryptOldPassword = DigestUtils.md5DigestAsHex((SALT + oldPwd).getBytes());
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("id", id);
        qw.eq("userPassword", encryptOldPassword);
        if (userService.getOne(qw) == null)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "原密码输入错误,再想一想!");
        User user = new User();
        String encryptNewPassword = DigestUtils.md5DigestAsHex((SALT + newPwd).getBytes());
        user.setId(id);
        user.setUserPassword(encryptNewPassword);
        boolean result = userService.updateById(user);
        if (!result)
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据库内部异常,修改失败");
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
            HttpServletRequest request) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,
            HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        return ResultUtils.success(userVOPage);
    }



    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
            HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("/normal")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> normalUser(@RequestBody IdRequest idRequest) {
        if (ObjectUtils.anyNull(idRequest, idRequest.getId()) || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = idRequest.getId();
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        user.setStatus(0);
        return ResultUtils.success(userService.updateById(user));
    }

    @PostMapping("/ban")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> banUser(@RequestBody IdRequest idRequest, HttpServletRequest request) {
        if (ObjectUtils.anyNull(idRequest, idRequest.getId()) || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = idRequest.getId();
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        Object userObj = StpUtil.getSession().get(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (id.equals(currentUser.getId()))
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "您差点就BAN掉自己了~");
        if (id.longValue() == 1871810916349243394L)
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "您不能BAN掉该尊贵的用户！！！");
        user.setStatus(1);
        return ResultUtils.success(userService.updateById(user));
    }

    /**
     * 添加用户签到记录
     *
     * @param request
     * @return 当前是否已签到成功
     */
    @PostMapping("/add/sign_in")
    public BaseResponse<Boolean> addUserSignIn(HttpServletRequest request) {
        // 必须要登录才能签到
        User loginUser = userService.getLoginUser(request);
        boolean result = userService.addUserSignIn(loginUser.getId());
        return ResultUtils.success(result);
    }

    /**
     * 获取用户签到记录
     *
     * @param year    年份（为空表示当前年份）
     * @param request
     * @return 签到记录映射
     */
    @GetMapping("/get/sign_in")
    public BaseResponse<List<Integer>> getUserSignInRecord(Integer year, HttpServletRequest request) {
        // 必须要登录才能获取
        User loginUser = userService.getLoginUser(request);
        List<Integer> userSignInRecord = userService.getUserSignInRecord(loginUser.getId(), year);
        return ResultUtils.success(userSignInRecord);
    }

    /**
     * 获取用户签到记录
     *
     * @param year    年份（为空表示当前年份）
     * @param otherUserId  用户id
     * @return 签到记录映射
     */
    @GetMapping("/get/other/sign_in")
    public BaseResponse<List<Integer>> getOtherUserSignInRecord(Integer year, long otherUserId) {
        List<Integer> userSignInRecord = userService.getUserSignInRecord(otherUserId, year);
        return ResultUtils.success(userSignInRecord);
    }

    // endregion
}
